﻿using Reference.Apps.Models.Entities;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using Windows.Data.Xml.Dom;
using Windows.Storage;
using Windows.Storage.Streams;

namespace Reference.Apps.Common
{
    public class StorageHelper
    {
        private const string RecentFile = "recent.xml";


        public async void WriteRecent(ObservableCollection<CodeGroup> groups)
        {
            var folder = ApplicationData.Current.LocalFolder;
            var recentFile = await folder.CreateFileAsync(RecentFile, CreationCollisionOption.ReplaceExisting);

            using (var s = await recentFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                using (IOutputStream os = s.GetOutputStreamAt(0))
                {
                    XmlSerializer xs = new XmlSerializer(typeof(ObservableCollection<CodeGroup>));
                    xs.Serialize(os.AsStreamForWrite(), groups);
                }
            }

        }

        public async Task<ObservableCollection<CodeGroup>> GetRecent()
        {
            var folder = ApplicationData.Current.LocalFolder;
            ObservableCollection<CodeGroup> resp = null;
            try
            {
                var recentFile = await folder.GetFileAsync(RecentFile);

                if (recentFile != null)
                {
                    using (IInputStream iss = await recentFile.OpenReadAsync())
                    {
                        XmlSerializer xs = new XmlSerializer(typeof(ObservableCollection<CodeGroup>));
                        resp = xs.Deserialize(iss.AsStreamForRead()) as ObservableCollection<CodeGroup>;
                    }
                }
            }
            catch { }
            return resp;


        }
    }
}
